<!doctype html>
<html>
<head>
  <title>人脸登陆</title>
  <meta charset="utf8">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <link href="css/index.css" rel="stylesheet"/>
  <link href="css/mui.min.css" rel="stylesheet" />
</head>
<body>
  <div class="topwrapper">
    <img src="img/back.png" width=15px height=16px id="back"></img>
    <span>人脸登陆</div>
  </div>
  <div class="content">
    <div class="btnwrapper">
      <div id="cambtn" class="btn">开始识别</div> 
      <div id="stop" class="btn">停止</div> 
    </div>
    <div></div>
    <!-- <div id="facelogin">
      <div>                  
        <video playsinline webkit-playsinline id="video"></video>
        <canvas id='canvas' width="100px" height="100px" style="display: none;"></canvas> 
      </div> 
      <div id="msg"></div>  
    </div> -->
    <div id="imgshow">
      <img src="" id="img" />
    </div>
    <div id="info">
      <div class="toptittle">
        <div class="line"></div>
        <div class="cont">
          <img src="img/zhuanjiaku.png" width=20px height=20px/>
          <span class="text">个人信息</span>
        </div>
        <div class="line"></div>
      </div>
      <div class="middletext">
        <div class="line">
          <img src="img/comp.png" width=15px height=15px/>
          <span>工号：</span>
          <span id="jobId"></span>
        </div>
        <div class="line">
          <img src="img/position.png" width=15px height=15px/>
          <span>姓名：</span>
          <span id="name" ></span>
        </div>
        <div class="line" id="agewrap">
          <img src="img/position.png" width=15px height=15px/>
          <span>年龄：</span>
          <span id="age"></span>
        </div>
        <div class="line" id="phonewrap">
          <img src="img/phone.png" width=15px height=15px/>
          <span>电话：</span>
          <span id="phone"></span>
        </div> 
        
      </div>  
    </div>
    <form id="form">
      <input id="file" name="file" type="file" accept= "image/*"/>
    </form> 
    <div id="loading" class="loading">
      加载中
    </div>
  </div>
  
</body>
</html>

<script src="js/jquery-1.9.1.js"></script>
<script>
  $(document).ready(function() {
    var video,canvas,vendorUrl,interval;
    var time = 0;
		var lock = 0;
    // 调用摄像头
    $('#cambtn').click(function() {
      $('#facelogin').show();
      video = document.getElementById('video'),
      canvas = document.getElementById('canvas'),
      navigator.getMedia =navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
      navigator.getMedia(
        {
          video: true, //使用摄像头对象
          audio: false //不适用音频
        }, 
        function(strem) {
    	    video.srcObject = strem; //window.HTMLMediaElement.srcObject(
          video.play();
        }, 
        function(error) {
          $('#msg').text(error)
        }
      );
      setTimeout('',5000); //1s之后
      interval = setInterval(getface,3000);
    })
    $('#stop').click(function(){
      lock = 1;
    })
    //自动拍照
    function getface(){
			if(lock == 1){
        return;
      }	
			//lock = 1;
      time ++;            
      canvas.getContext('2d').drawImage(video, 0, 0, 100, 100);
      var bdata = canvas.toDataURL("image/jpeg");
      var base64 = bdata.split(',')[1];//照片压缩成base位数据
      console.log(bdata);
      var $d = document.querySelector("#img");//图片本身元素
      var $imgshow = document.querySelector("#imgshow");//图片容器
      $d.setAttribute("src", bdata);//给图片地址,显示缩略图
      $imgshow.style.display="block";//样式显示

      var bytes = window.atob(base64);
      var array = [];
      for(var i = 0; i < bytes.length; i++){
        array.push(bytes.charCodeAt(i));
      }
      var blob = new Blob([new Uint8Array(array)],{type:'image/jpeg'});
      var formData = new FormData();
      formData.append('file',blob, Date.now() + '.jpg');
      
      // formData.append('fileBase64',base64)
      // console.log('======chenjia=====',$('#file').val())
      //var formData = new FormData($('#form')[0]);// 自动搜索表单信息(表单内没有name属性的input不会被搜索到)，IE<=9不支持FormData

      $.ajax({
         type: 'post',
         url: 'http://10.1.100.178:8080/ttface/facesearch',
         data: formData,
         contentType: false,// 当有文件要上传时，此项是必须的，否则后台无法识别文件流的起始位置(详见：#1)
         processData: false,// 是否序列化data属性，默认true(注意：false时type必须是post，详见：#2)
         // xhr: xhrOnProgress(function(e){// (详见：#3)
         //        var percent = e.loaded / e.total * 100;//计算百分比
         //        var $load = document.querySelector("#loading");
         //        $load.style.display = "block";
         //        $("#loading").text("识别中 ：" + Math.round(percent) + "%")
         //        //$('body').append('->'+ percent);
         //  }),
         success: function(data) {
           var $load = document.querySelector("#loading");
           $load.style.display = "none";
           console.log(data)
           if(data.code === 11111){
             alert('操作失败')
             $("#msg").text('没有匹配到')
             lock = 0;
           }
           if(data.code === 10000){
             if(data.data && data.data.result === "-1"){
               // alert("登陆失败，请重新上传图片！")
               $("#msg").text('没有匹配到')
               lock = 0;
             }  
             if(data.data && data.data.result === "1"){
               var user = data.data.user
               alert("登陆成功")
               clearInterval(interval);//清除定时器
               var $info = document.querySelector("#info");
               var $agewrap = document.querySelector("#agewrap");
               var $phonewrap = document.querySelector("#phonewrap");
               $info.style.display = "block";//显示个人信息的工号和姓名
               $("#jobId").text(user.jobId)
               $("#name").text(user.name)
               $("#age").text('')
               $("#phone").text('')
               if(user.age !== null){
                 $("#age").text(user.age)
               }
               if(user.phone !== null){
                 $("#phone").text(user.phone)
               }
             }    
           }
         },
         error: function(XMLHttpRequest, textStatus, errorThrown) {
           console.log(XMLHttpRequest.readyState);
           console.log(textStatus);
           console.log(errorThrown);
           lock = 0;
         }
       })
    }
    // 监听上传进度
    var xhrOnProgress = function(fun) {
      xhrOnProgress.onprogress = fun; //绑定监听
      return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
          return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
          xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
      }
    }
    $('#back').click(function() {
      window.location.href= './index.html'
    })
    

    
  })
</script>
